package com.duobaoyu.dby.supply.biz.interceptor;


import com.duobaoyu.dby.channel.common.util.SpringContextHolderUtils;
import com.duobaoyu.dby.supply.biz.client.resource.ResourceApiClient;
import com.duobaoyu.dby.supply.biz.client.resource.bean.bo.BusinessConfigBO;
import com.duobaoyu.dby.supply.biz.constant.SupplyChainConstants;
import com.duobaoyu.dby.supply.biz.util.ThreadLocalUtils;
import com.duobaoyu.dby.supply.core.common.exception.CustomAssert;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName DynamicTableInterceptor
 * @Description 动态表名拦截器
 * @createTime 08:51:00 2022/08/18
 */
@Slf4j
@Order(100)
@NoArgsConstructor
public class BizCodeInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
		String bizCode = request.getHeader(SupplyChainConstants.BIZ_CODE);
		CustomAssert.hasLength(bizCode,"authentication exception:request header biz_code does not exist");
		ResourceApiClient resourceApiClient = SpringContextHolderUtils.getBean(ResourceApiClient.class);
		BusinessConfigBO bizCodeInfo = resourceApiClient.getBizCodeInfo(bizCode);
		CustomAssert.notNull(bizCodeInfo, "bizCode does not exist");
		ThreadLocalUtils.put(SupplyChainConstants.BIZ_CODE, bizCode);
		return HandlerInterceptor.super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}


	@Override
	public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
		ThreadLocalUtils.remove();
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
}
